/**
 * Class EntityInfoModule.
 * 
 * @author Maxime Ollagnier
 */
EntityInfoModule.inherits(Module);
function EntityInfoModule() {
	this.entity = undefined;
	var that = this;

	this.inputName = new InputTextModule({
		'id' : 'inputName',
		'label' : I18n.get('name'),
		'placeholder' : I18n.get('name'),
		'validationPattern' : ValidationPattern.VALID_DEFAULT,
		'mandatory' : true
	});
	this.inputParent = new InputReferrerModule({
		'id' : 'inputParent',
		'label' : I18n.get('entity.parent'),
		'selectableType' : UserManager.TYPE_ENTITY,
		'mandatory' : true,
		'displayCreditors' : false,
		'onSelect' : function(){ 
			that.checkDeleteFlow();
			that.refreshIcs();
		}
	});
	this.inputNne = new InputTextModule({
	    'id' : 'inputNne',
		'label' : I18n.get('creditor.info.nne.label'),
		'placeholder' : I18n.get('creditor.info.nne.label'),
		'validationPattern' : ValidationPattern.VALID_NNE
	});
	this.inputIcs = new InputTextModule({
	    'id' : 'inputIcs',
		'label' : I18n.get('creditor.info.ics.label'),
		'placeholder' : I18n.get('creditor.info.ics.label'),
		'validationPattern' : ValidationPattern.VALID_ICS,
		'onKeyUp' : function(value) {
			if (value == ""){
				that.inputNne.setValue("");
			}
			that.inputNne.setReadonly(value == "").buildJQ();
		},
		'onBlur' : function(value) {
			that.inputIcs.setValue(that.inputIcs.value.toUpperCase()).buildJQ();
		}
	});
	this.inputType = new InputSelectModule({
        'id' : 'inputType',
		'mandatory' : true,
		'label' : I18n.get('type'),
		'options' : EnumManager.EntityType
	});
	
	this.buttonGetIcs = $('<a href="javascript:;" style="text-decoration:underline;">' + I18n.get('entity.info.getIcs') + '</a>').click(function() { that.getIcs(); });
	this.msgNotUpdatable = $('<i>' + I18n.get('entity.info.msgNotUpdatable') + '</i>');
}

EntityInfoModule.neededRoles = ['VIEW_ORGANIZATION_ENTITY'];

EntityInfoModule.prototype.fillJQ = function(jQ) {
	var that = this;
	
	jQ.append($('<h5>' + I18n.get('infos') + '</h5>'));

	var jQForm = $('<div class="form well cropbottom row-fluid"></div>');
	jQ.append(jQForm);
	
	var columnLeft = $('<div class="span6" style="text-align:left;"></div>');
	columnLeft.append(this.inputName.buildJQ());
	columnLeft.append(this.inputIcs.buildJQ().hide());
	columnLeft.append(this.inputNne.buildJQ().hide());
	columnLeft.append(this.buttonGetIcs.hide());
	columnLeft.append(this.msgNotUpdatable.hide());
	this.inputIcs.onKeyUp(this.inputIcs.value);
	var columnRight = $('<div class="span6"></div>');
	columnRight.append(this.inputType.buildJQ());
	if (this.entity != UserManager.user.referrer) {
		columnRight.append(this.inputParent.buildJQ());
	} else {
		this.inputParent.setMandatory(false);
	}
	jQForm.append(columnLeft).append(columnRight);
	
	// Buttons
	var buttonRow = $('<div class="btn-row"></div>');
	jQForm.append(buttonRow);
	
	this.buttonSave = $('<div class="btn save">' + I18n.get('save') + '</div>');
	this.buttonSave.click(function() { that.save(); });
	buttonRow.append(this.buttonSave);
	
	if (Util.checkObject(this.entity) && this.entity.children.length == 0) {
		var buttonDelete = $('<div class="btn delete">' + I18n.get('delete') + '</div>');
		buttonDelete.click(function() { that.deleteEntity(); });
		buttonRow.append(buttonDelete);
	}
};

/**
 * Loads the entity directly from the parameters
 */
EntityInfoModule.prototype.loadData = function(callback) {
	var that = this;
	
	this.setEntity(this.parameters.referrer);
	this.refreshIcs();
	Util.getFunction(callback)();
	
	if (Util.check(this.parameters.referrer)) {
		if (Util.checkString(this.parameters.referrer.ics)){
			if (this.parameters.referrer.parentHasIcs){
				this.inputNne.setReadonly(true).buildJQ();
				this.inputIcs.setReadonly(true).buildJQ();
			}
			this.inputNne.getJQ().show();
			this.inputIcs.getJQ().show();
		} else {
			AjaxManager.getJSON('getICSinHierarchy', {
				'referrerId' : this.parameters.referrer.id
			}, function(result) {
				if (result.success) {
					if (result.status == 0){
						// no ICS found in hierarchy
						that.inputNne.getJQ().show();
						that.inputIcs.getJQ().show();
					} else if(result.status == 1){
						// one distinct ICS found in hierarchy
						that.inputNne.setReadonly(true).buildJQ();
						that.inputIcs.setReadonly(true).buildJQ();
						that.inputNne.getJQ().show();
						that.inputIcs.getJQ().show();
						that.buttonGetIcs.show();
						that.idCreditorSEPA = result.idCreditorSEPA;
					} else {
						// more that one ICS found in hierarchy
						that.msgNotUpdatable.show();
					}
				}
			});
		}
	} else {
		this.inputNne.getJQ().show();
		this.inputIcs.getJQ().show();
	}
};

/**
 * Sets the entity
 */
EntityInfoModule.prototype.setEntity = function(entity) {
	this.entity = entity;
	if (!Util.checkObject(this.entity)) {
		return;
	}

	this.inputName.setValue(this.entity.name);
	this.inputParent.setValue(UserManager.getReferrer(this.entity.parentId));
	this.inputParent.setDisabledReferrers([this.entity]);
	this.inputType.setValue(this.entity.type);
	this.inputNne.setValue(this.entity.nne);
	this.inputIcs.setValue(this.entity.ics);
	if (this.inputIcs.getValue() != ""){
		this.inputIcs.setMandatory(true).buildJQ();
	}
};

EntityInfoModule.prototype.getIcs = function() {
	var that = this;
	
	PopupModule.getInstance().clear();
	PopupModule.getInstance().setTitle(I18n.get('entity.getics.warning'));
	PopupModule.getInstance().setContent('<div style="text-align:left;">' + I18n.get('entity.getics.warning.content') + '</div>');
	PopupModule.getInstance().addButton('OK', function(){
		that.inputNne.setValue(that.idCreditorSEPA.nne).buildJQ();
		that.inputIcs.setValue(that.idCreditorSEPA.ics).buildJQ();
		that.save();
	});
	PopupModule.getInstance().addButton(I18n.get('cancel'));
	PopupModule.getInstance().show();
	
};

/**
 * Sets the entity
 */
EntityInfoModule.prototype.save = function() {
	var that = this;
	if (!this.validate()) {
		return false;
	}
	
	var entity = {};
	if (Util.checkObject(this.entity)) {
		entity.id = this.entity.id;
	}
	entity.name = this.inputName.value;
	entity.type = this.inputType.value;
	if (this.inputIcs.value != ""){
		entity.ics = this.inputIcs.value;
	}
	if (this.inputNne.value != ""){
		entity.nne = this.inputNne.value;
	}
	if (Util.checkObject(this.inputParent.value)) {
		entity.parentId = this.inputParent.value.id;
	}
		
	AjaxManager.getJSON('saveEntity', {
		'entity' : JSON.stringify(entity)
	}, function(result) {
		if (result.success) {
			PopupModule.getInstance().clear();
			PopupModule.getInstance().setTitle(I18n.get('success'));
			PopupModule.getInstance().setContent(I18n.get('entity.saved'));
			PopupModule.getInstance().addButton('OK');
			UserManager.setReferrer(result.entity);
			if (Util.checkObject(that.entity)) {
				result.entity.expanded = that.entity.expanded;
				that.load({ 'referrer' : result.entity }, function() { PopupModule.getInstance().show(); });
			} else {
				NavigationManager.goTo('ReferrerPage?referrerId=' + result.entity.id + '&type=' + result.entity.type);
				PopupModule.getInstance().show();
			}
		}
	});
	return true;
};

EntityInfoModule.prototype.checkDeleteFlow = function(){
	if (Util.checkObject(this.entity)) {
		EntityInfoModule.doCheckDeleteFlow(this.entity.id, this.inputParent.getValue().id, false);
	}
};

EntityInfoModule.doCheckDeleteFlow = function(referrerId, newParentId, creditorType){
	AjaxManager.getJSON('getDeleteFlow', {
		'referrerId' : referrerId,
		'newParentId' : newParentId
	}, function(result) {
		if (result.success){
			var content = '<div style="text-align:left;">';
			var hasWarn = false;
			if (result.isUserWithFlow){
				hasWarn = true;
				content += creditorType ? I18n.get('referrer.info.creditor.userWithflow') : I18n.get('referrer.info.referrer.userWithflow');
			}
			if (result.toBeDeletedLength > 0){
				if (hasWarn){
					content += '<br/><br/>';
				}
				hasWarn = true;
				content += creditorType ? I18n.get('referrer.info.creditor.move') : I18n.get('referrer.info.referrer.move') + '<br/><ul style="text-align:left;margin-left:50px;">';
				$.each(result.toBeDeleted, function(id, mandateFlow) {
					content += '<li>' + mandateFlow.name + '</li>';
				});
				content += '</ul>';
			}
			if (hasWarn){
				content += '</div>';
				PopupModule.getInstance().show({
					'title' : I18n.get('referrer.info.referrer.moveT'),
					'content' : content,
					'button0' : { 'text' : 'OK' }
				});
			}
		}
	}, true);
};

/**
 * Deletes the entity
 */
EntityInfoModule.prototype.deleteEntity = function() {
	var that = this;
	if (!Util.checkObject(this.entity)) {
		return;
	}
	PopupModule.getInstance().clear();
	PopupModule.getInstance().setTitle(I18n.get('confirmation'));
	PopupModule.getInstance().setContent(I18n.get('entity.delete.confirmation'));
	PopupModule.getInstance().setContent(I18n.get('entity.delete.confirmation'));
	PopupModule.getInstance().addButton('Cancel');
	PopupModule.getInstance().addButton('OK', function() {
		AjaxManager.getJSON('deleteEntity', {
			'entityId' : JSON.stringify(that.entity.id)
		}, function(result) {
			if (result.success) {
				UserManager.deleteReferrer(that.entity.id);
				NavigationManager.goTo('ReferrersPage');
			}
		});
	});
	PopupModule.getInstance().show();
};

/**
 * Refresh ICS and NNE fields according to selected parent
 */
EntityInfoModule.prototype.refreshIcs = function(callback) {
	var parent = this.inputParent.getValue();
	if (!Util.checkObject(this.entity)) {
		if (Util.check(parent) && Util.checkString(parent.ics)){
			this.inputIcs.setValue(parent.ics);
			this.inputNne.setValue(parent.nne);
		} else {
			this.inputIcs.setValue("");
			this.inputNne.setValue("");
		}
		this.inputParent.setFilter({});
	} else {
		this.inputParent.setFilter({'ics':this.inputIcs.getValue(), 'highlight':false, 'displayEmpty':true});
	}
	if (Util.check(parent) && Util.checkString(parent.ics)){
		this.inputIcs.setReadonly(true).buildJQ();
		this.inputNne.setReadonly(true).buildJQ();
	} else {
		this.inputIcs.setReadonly(false).buildJQ();
		this.inputIcs.onKeyUp(this.inputIcs.value);
	}
};
